#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : tornado_server.py

import tornado.web
import tornado.ioloop
import pandas as pd
from concurrent.futures import ThreadPoolExecutor


class Tornado_http:

    def __init__(self, port=8888):

        self.port = port
        self.handlers = []
        self.executor = ThreadPoolExecutor(max_workers=1)


    def set_port(self, port):
        self.port = port


    # 添加路由
    def add_handler(self, handler_addr, re_fun, *args):
        """
        :param handler_addr: 路由地址
        :param re_fun: 视图函数
        :param args: 路由参数
        :return:
          """
        class handlername(tornado.web.RequestHandler):
            def get(self):
                argsl = []
                for arg in args:
                  argsl.append(self.get_query_argument(arg))
                res = re_fun(*argsl)
                if isinstance(res, dict):
                  self.write(res)
                elif isinstance(res, bytes):
                  self.write(res)
                elif isinstance(res, str):
                  self.write(res)
                elif isinstance(res, pd.DataFrame):
                  self.write(res.to_json())
                else:
                    print("请设置视图函数返回值为 字符串、字典型 或 pd.DataFrame")

            def post(self):
                argsl = []
                for arg in args:
                   argsl.append(self.get_argument(arg))
                res = re_fun(*argsl)
                if isinstance(res, dict):
                    self.write(res)
                elif isinstance(res, bytes):
                    self.write(res)
                elif isinstance(res, str):
                    self.write(res)
                elif isinstance(res, pd.DataFrame):
                    self.write(res.to_json())
                else:
                    print("请设置视图函数返回值为 字符串、字典型 或 pd.DataFrame")
        self.handlers.append((handler_addr, handlername))


    # todo add_handler 能否更改为 装饰器方式 更简洁
    def route(self, rule, *args1):
        def wrapper(func):
            def inner_wrapper(*args, **kwargs):
                class handlername(tornado.web.RequestHandler):

                    def get(self):
                        argsl = []
                        for arg in args:
                            argsl.append(self.get_query_argument(arg))
                        self.write(func(*argsl))
                self.handlers.append((rule, handlername))
                return func(*args, **kwargs)
            return inner_wrapper
        return wrapper



    # 开启 tornado 服务
    def start_http_server(self):
        app = tornado.web.Application(self.handlers)
        app.listen(port=self.port, address="0.0.0.0")
        # 启动web程序，开始监听端口的连接
        self.executor.submit(tornado.ioloop.IOLoop.current().start)
        print(f"已经部署service在端口{self.port}")


# 获取 tornado 实例
server = Tornado_http()